// pages/views/login/login.js
const utils = require('../../../utils/util.js');
const root = getApp().globalData.rooturl;
const RSA = require('../../../utils/rsa.js');
const key = require('../../../utils/key.js').key;
import {wxlogin} from '../../../utils/imgbase64.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
      phone:"",
      phonecode:"",
      codewait:'',
      getcodestate:'0',
      lbdis:false,
      cbdis:false,
      isloading:false,
      hasloading:false,
      btnstate:'获取验证码',
      wxid:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      this.setData({
          wxlogin
      })
  },
  //输入监听
  phoneInp: function (e) {
      this.setData({
          phone: e.detail.value
      })
  },
  codeInp: function (e) {
      this.setData({
          phonecode: e.detail.value
      })
  },
  //获取验证码
  getCode:function(){
      let _this = this;
      if (utils.empty(this.data.phone) == false) {
          utils.errorToast('手机号不能为空');
          return false;
      }
      if (utils.isPhone(this.data.phone) == false) {
          utils.errorToast('请输入正确格式手机号');
          return false;
      }
      this.setData({
          cbdis: true,
          hasloading: true
      })
      //获取验证码请求
      utils.ajax(root +'wechatusers/SendPhoneVcode', {
          header: {
              SOURCE:'wechatApp',
              "Content-Type": 'application/x-www-form-urlencoded'
          },
          data:{
              phone: this.data.phone,
              type:'login',
              restType: 0
          },
          method:'post'
      }, function (res) {
            if(res.code=="1"||res.code=='2001'){
                wx.showToast({
                    title:'验证码发送成功',
                    icon:'none'
                })
                _this.setData({
                    hasloading: false
                })
                utils.setCodeBtn('codewait1', 60, _this);
            }else{
                wx.showToast({
                    title: '验证码发送失败,请稍后再试',
                    icon:'none'
                })
                _this.setData({
                    cbdis: false,
                    hasloading: false
                })
            }
      },function(res){
          wx.showToast({
              title: '网络错误，请求失败',
              icon:'none'
          })
          _this.setData({
              cbdis: false,
              hasloading: false
          })
      })
  },
  //登录
  pushLogin:function(e){
      let _this = this;
      if (utils.empty(this.data.phone)==false){
         utils.errorToast('手机号不能为空');
         return false;
      }
      if (utils.isPhone(this.data.phone)==false) {
          utils.errorToast('请输入正确格式手机号');
          return false;
      }
      if (utils.empty(this.data.phonecode)==false) {
          utils.errorToast('验证码不能为空');
          return false;
      }
      this.setData({
          lbdis:true,
          isloading:true
      })
      this.sendLogin(this.data.phone,this.data.phonecode)
  },
  //发送登录请求
  sendLogin:function(phone,phonecode){
      //参数加密
      let _this = this;
      let data =  this.encrypt(phone,phonecode);
      utils.ajax(root +"wechatusers/Login",{
          method:'post',
          header:{
              "SOURCE":'wechatApp',
              "Content-Type": 'application/x-www-form-urlencoded'
          },
          data:{
              restType: 0,
              data:data
          },
      },function(res){
           if(res.code=='1'){
               wx.showToast({
                   title: '登录成功',
                   icon:'none'
               })
               res.data.timeout = new Date().getTime();
               wx.setStorageSync('user_info', res.data);
               //发送用户信息
               utils.sendUserMsg(res.data);
               _this.setData({
                   lbdis: false,
                   isloading: false,
               })
               wx.switchTab({
                   url: '../../index/index'
               })
           }else{
               wx.showToast({
                   title: '登录失败，请检查网络',
                   icon: 'none'
               })
               _this.setData({
                   lbdis: false,
                   isloading: false,
               })
           }
      },function(err){
           _this.setData({
               lbdis: false,
               isloading: false,
           })
           wx.showToast({
               title: '登录失败，请检查网络',
               icon: 'none'
           })
      })
  },
  //参数加密
  encrypt:function(phone,phonecode){
      let rsa_type = new RSA.RSAKey();
      rsa_type = RSA.KEYUTIL.getKey(key);
      let arg = {
          phone:phone,
          code:phonecode
      };
      let encStr = rsa_type.encrypt(JSON.stringify(arg))
      encStr = RSA.hex2b64(encStr);
      return encStr;
  },
 // 获取微信oppenid
  wxLogin: function (){
      let _this = this;
      wx.showLoading({
          title:'获取用户信息',
          icon:'none'
      })
      wx.login({
          complete:(res)=>{
              if(res.code){
                wx.getUserInfo({
                  withCredentials:true,
                  success:(msg)=>{
                    if(msg){
                      //通过code获取微信用户信息                  
                      this.getWxMsg(res.code, msg.encryptedData,msg.iv);
                    }
                  }
                })
              }else{
                wx.hideLoading();
                wx.showToast({
                    title: '获取信息失败，网络错误1',
                    icon:'none'
                })
              }
          }
      })
  },
  getWxMsg: function (code,encryptedData,iv){
      let _this = this;
      utils.ajax(root + 'wechats/WechatAuth', {
          header: {
              "SOURCE": 'wechatApp',
              "Content-Type": 'application/x-www-form-urlencoded'
          },
          data: {
              code:code,
              encryptedData:encryptedData,
              iv:iv,
              restType: 0
          },
          method: 'post'
      }, function (res) {
          if (res.code == "1") {
              let wxid = res.data.openid, wx_unionid = res.data.wx_unionid;
              _this.setData({
                  wxid: wxid
              })
              let rsa_type = new RSA.RSAKey();
              rsa_type = RSA.KEYUTIL.getKey(key);
              let arg = {
                  wx_id: wxid,
                  wx_unionid: wx_unionid,
                  restType: 0
              };
              console.log(arg)
              let encStr = rsa_type.encrypt(JSON.stringify(arg))
              encStr = RSA.hex2b64(encStr);
              _this.sendWXLogin(encStr)
          } else {
              wx.hideLoading();
              wx.showToast({
                  title: '获取信息失败，网络错误',
                  icon: 'none'
              })
          }
      })
  },
  //发送微信登录请求
  sendWXLogin:function(data){
      let _this = this;
      //微信登录
      wx.request({
          url: root + 'wechatusers/WxLogin',
          header: {
              "SOURCE": 'wechatApp',
              "Content-Type": 'application/x-www-form-urlencoded'
          },
          data: {
              restType: 0,
              data: data
          },
          method: 'POST',
          success:res=>{
              if (res.data.code == -3001) {
                  _this.jumpCellPhone();
              } else if (res.data.code == 1) {
                  wx.hideLoading();
                  wx.showToast({
                      title: '登录成功',
                      icon: 'none'
                 })
                  res.data.data.timeout = new Date().getTime();
                  wx.setStorageSync('user_info', res.data.data);
                  //发送用户信息
                  utils.sendUserMsg(res.data.data);
                  wx.switchTab({
                      url: '../../index/index'
                  })
              }else {
                  wx.hideLoading();
                  wx.showToast({
                      title: '登录失败，请检查网络',
                      icon: 'none'
                  })
              }
          },
          fail:function(){
              wx.hideLoading();
              wx.showToast({
                  title: '获取信息失败，请检查网络',
                  icon: 'none'
              })
          }
      })
  },
  getwxInfo:function(e){
    if (e.detail.userInfo!=false){
      this.avatar = e.detail.userInfo.avatarUrl;
      this.nickName = e.detail.userInfo.nickName;
      this.wxLogin();
    }else{
      wx.showToast({
        title:"获取授权失败",
        icon:"none"
      })
    }
  },
  jumpCellPhone:function(){
    let pic = this.avatar;
    let nickname = this.nickName;
    wx.redirectTo({
      url: '../cellphone/cellphone?pic=' + pic + '&openid=' + this.data.wxid + '&nickname=' + nickname
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  
  // }
})